package org.eggdo.apof.server;

import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.image.*;

import com.sun.image.codec.jpeg.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class for Servlet: Draw
 * 
 */
public class Draw_backup extends javax.servlet.http.HttpServlet implements
		javax.servlet.Servlet {
	static final long serialVersionUID = 1L;

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#HttpServlet()
	 */
	public Draw_backup() {
		super();
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("image/jpeg");
		createImage(response.getOutputStream());
	}

	/*
	 * (non-Java-doc)
	 * 
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request,
	 *      HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	private void createImage(OutputStream out) {
		// int width = 700;
		int width = 800;
		int height = 600;
		BufferedImage bi = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics2D g = bi.createGraphics();
		// set background:
		g.setBackground(Color.pink);
		g.setColor(Color.green);
		Font font = new Font("", Font.PLAIN, 12);
		g.setFont(font);

		XmlParser xp =new XmlParser("http://api.fanfou.com/statuses/user_timeline.rss?id=abcx");

		g.drawString(xp.getTitle(), 15, 20);
		ArrayList<Item> items = xp.getItems();
		int y = 50;

		try {
			for (Iterator<Item> itr = items.iterator(); itr.hasNext();) {
				Item nd = (Item) itr.next();
				g.drawString(nd.getTitle(), 30, y);
				y += 20;
			}
		} catch (NullPointerException e) {
			e.printStackTrace();
		}

		// end draw:
		g.dispose();
		bi.flush();
		// encode:
		JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
		JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bi);
		param.setQuality(1.0f, false);
		encoder.setJPEGEncodeParam(param);
		try {
			encoder.encode(bi);
		} catch (IOException ioe) {
			ioe.printStackTrace();
		}
	}

}